<template>
  <div v-loading="verifiedLoading" element-loading-text="认证中，请稍后...">
    <el-form :model="userInfo" label-width="150px" ref="userInfo">
      <el-form-item label="更换名片图" prop="newAddFileId">
        <el-upload
          :class="{ hide: isHideUploadEdit }"
          ref="uploadAvatar"
          list-type="picture-card"
          :action="uploadBaseUrl"
          :data="{ filetype: '更换名片图', app: 'shulan', module: '2', sourceKey: '1' }"
          :limit="2"
          :before-upload="onUploadBefore"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :on-exceed="onUploadExceed"
          :on-remove="onUploadRemove"
          accept=".jpg,.jpeg,.png"
          :multiple="true"
          :file-list="avatarPreviewList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="经纪人真实姓名" prop="realName" :rules="[{ required: true, message: '姓名不能为空' }]">
        <el-input v-model.number="userInfo.realName"></el-input>
      </el-form-item>
      <el-form-item label="合作业务手机号" prop="mobile" :rules="[{ required: true, validator: validatePass }]">
        <el-input v-model="userInfo.mobile"></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="city" :rules="[{ required: true, message: '城市不能为空' }]">
        <el-select v-model="userInfo.city" filterable placeholder="请选择" clearable style="width: 100%">
          <el-option v-for="item in cityOptions" :key="item.code" :label="item.city" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="shopShortName" :rules="[{ required: true, message: '品牌不能为空' }]">
        <el-select
          v-model="userInfo.shopShortName"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteShopHandler"
          :loading="loading"
          style="width: 100%"
          @change="handleChangeShop"
        >
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopShortName"
            :value="item.shopId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="门店" prop="storeName" :rules="[{ required: true, message: '门店不能为空' }]">
        <el-select
          v-model="userInfo.storeName"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteStoreHandler"
          :loading="loading"
          @change="handleChangeStore"
        >
          <el-option v-for="item in storeOptions" :key="item.storeId" :label="item.storeName" :value="item.storeId">
            <div style="float: left">{{ item.storeName }}</div>
            <div style="float: right; color: #8492a6; font-size: 13px">{{ item.storeAddr }}</div>
          </el-option>
        </el-select>
        <span v-hasPermi="['reviewActivities:memberManage:manual']" style="margin-left: 10px">
          没有想搜的门店，
          <span style="color: red; cursor: pointer" @click="showPop">手工创建</span>
        </span>
      </el-form-item>
      <el-form-item label="门店地址" prop="storeAddr" :rules="[{ required: true, message: '门店地址不能为空' }]">
        <el-input v-model="userInfo.storeAddr"></el-input>
      </el-form-item>
      <el-form-item label="认证责任人" prop="saleUserName" :rules="[{ required: true, message: '认证责任人不能为空' }]">
        <el-select
          v-model="userInfo.saleUserName"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteSaleUserHandler"
          :loading="loading"
          @change="handleChangeSaleUser"
          style="width: 100%"
        >
          <el-option
            v-for="item in saleUserOptions"
            :key="item.saleUserId"
            :label="item.saleUserName"
            :value="item.saleUserName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="type===3">
        <el-button @click="cancelBut">取消认证</el-button>
        <el-button type="primary" @click="saveConfirm('userInfo')" :disabled="!submitAble">保存并更新认证</el-button>
      </el-form-item>
      <el-form-item v-else>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submitForm('userInfo')" :disabled="!submitAble">提交</el-button>
      </el-form-item>
    </el-form>

    <!-- 手工创建门店弹层 -->
    <el-dialog
      width="600px"
      title="门店新建"
      :visible.sync="createShopVisible"
      :close-on-click-modal="false"
      append-to-body
    >
      <create-shop-pop @onclose="createShopVisible = false" @oncreateshop="handleCreateShop"></create-shop-pop>
    </el-dialog>
  </div>
</template>
<script>
import {
  searchStore,
  searchSaleName,
  getUserInfo,
  userVerified,
  searchShop,
  onlineauthentication
} from "@/api/reviewActivities/memberManage";
import CITYS from "@/utils/config/citys";
import CreateShopPop from "./com/create-shop-pop";

export default {
  components: {CreateShopPop},
  props: {
    userId: {
      type: String,
      default: "",
    },
    type:{
      type:Number,
      default: ""
    },
    mobile:{
      type:String,
      default:'',
    }
  },
  data() {
    //合作业务手机号正则判断
    this.validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入合作业务手机号"));
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("合作业务手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    this.uploadBaseUrl = `https://${
      location.hostname === "mgr.shulanfd.com" ? "api" : "api-dev"
    }.shulanfd.com/aist-filesvr-web/api/files`;
    return {
      isCustumShop: false,
      createShopVisible: false,
      verifiedLoading: false,
      loading: false,
      cityOptions: [],
      storeOptions: [],
      shopOptions: [],
      saleUserOptions: [],
      userInfo: {
        city: "", // 城市
        userId: "", // 用户id
        realName: "", // 真实姓名
        mobile: "", //合作业务手机号
        saleUserId: "", // 责任人id
        saleUserName: "", // 认证责任人
        storeId: "", // 门店id
        storeName: "", // 门店
        storeAddr: "", // 门店地址
        shopId: "", //品牌id
        shopShortName: "", //品牌名称
        newAddFileId: [], //名片头像
        onlineOffline: 2, //   线上/线下审核 1:线上  2:线下
      },
      // 更换名片图
      isHideUploadEdit: false,
      avatarPreviewList:[]
    };
  },
  async created() {
    this.cityOptions = CITYS.map((item) => {
      return { ...item, value: item.city.replace("市", "") };
    });
    if(this.type===3){
     await this.getCardInfo()
    } else {
      for (var i in this.cityOptions) {
        if (this.cityOptions[i].city === "上海市") {
          this.userInfo.city = this.cityOptions[i].city;
        }
      }
      this.userInfo.mobile = this.mobile
    }
    
  },
  mounted() {
    this.userInfo.userId = this.userId;
  },
  watch: {
    "avatarPreviewList.length": function(newValue, oldValue) {
      this.isHideUploadEdit = newValue >= 2;
    }
  },
  computed: {
    submitAble() {
      return Object.keys(this.userInfo).every((key) => {
        if (key == "storeId" && this.isCustumShop) return true;
        if (key == "shopId" && this.isCustumShop) return true;
        return !!this.userInfo[key];
      });
    },
  },
  methods: {
    handleCreateShop(e) {
      const { city, shopShortName, storeName, storeAddr } = e;
      const id = "-"; //标志符
      this.userInfo.city = city;
      this.userInfo.storeId = id;
      this.userInfo.storeName = storeName;
      this.userInfo.storeAddr = storeAddr;
      this.storeOptions = [{ storeAddr, storeId: id, storeName }];

      this.userInfo.shopId = id;
      this.userInfo.shopShortName = shopShortName;
      this.shopOptions = [{ shopId: id, shopShortName }];
      this.isCustumShop = true;
    },
    showPop() {
      this.createShopVisible = true;
    },
    submitForm(userInfo) {
      this.$refs[userInfo].validate((valid) => {
        if(valid){
          let param = { ...this.userInfo };
          // 提交时还原标识符
          if (param.storeId == "-") param.storeId = "";
          if (param.shopId == "-") param.shopId = "";
          this.verifiedLoading = true;
          userVerified(Object.assign({}, param, { type: 1 })).then(({ data }) => {
            this.verifiedLoading = false;
            if (data.isSuccess) {
              this.$message({ type: "success", message: `认证成功！`, duration: 3000 });
              this.close();
              this.$emit("onrefresh");
            } else {
              this.$message({ type: "error", message: data.errorMessage, duration: 3000 });
            }
          });
        }
      })
    },
    remoteStoreHandler(query) {
      if (query !== "") {
        this.loading = true;

        searchStore({
          storeName: query,
          page: 1,
          pageSize: 99,
        }).then(({ data }) => {
          this.loading = false;
          if (data.isSuccess && data.content) {
            this.storeOptions = data.content.rows;
          }
        });
      } else {
        this.storeOptions = [];
      }
    },

    // 品牌
    remoteShopHandler(query) {
      if (query !== "") {
        this.loading = true;
        searchShop({
          shopShortName: query,
          page: 1,
          pageSize: 99,
        }).then(({ data }) => {
          this.loading = false;
          if (data.isSuccess && data.content) {
            this.shopOptions = data.content.rows;
          }
        });
      } else {
        this.shopOptions = [];
      }
    },

    remoteSaleUserHandler(query) {
      if (query !== "") {
        this.loading = true;

        searchSaleName({
          saleUserName: query,
          page: 1,
          pageSize: 99,
        }).then(({ data }) => {
          this.loading = false;
          if (data.isSuccess && data.content) {
            this.saleUserOptions = data.content.rows;
          }
        });
      } else {
        this.saleUserOptions = [];
      }
    },

    handleChangeStore(e) {
      let item = this.storeOptions.find((v) => v.storeId == e);
      this.userInfo.storeName = item.storeName;
      this.userInfo.storeId = item.storeId;
      this.userInfo.storeAddr = item.storeAddr;
    },

    handleChangeShop(e) {
      let item = this.shopOptions.find((v) => v.shopId == e);
      this.userInfo.shopId = item.shopId;
      this.userInfo.shopShortName = item.shopShortName;
    },

    handleChangeSaleUser(e) {
      let item = this.saleUserOptions.find((v) => v.saleUserName == e);
      this.userInfo.saleUserId = item.saleUserId;
    },

    close() {
      this.$emit("onclose");
    },

    //更换名片图
    onUploadSuccess(res, file, fileList) {
      if (res && res.length) {
        this.userInfo.newAddFileId = this.userInfo.newAddFileId.concat(res[0].id);
      } else {
        this.$message.error("图片上传失败");
      }
      this.isHideUploadEdit = fileList.length >= 2;
      this.$refs.userInfo.validateField("newAddFileId");
    },
    onUploadError() {
      this.$message.error("图片上传失败");
    },
    onUploadExceed() {
      this.$message.error("最多只能上传两张名片图");
    },
    onUploadBefore(file) {
      let isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      if (!isJPG) {
        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
      }
      return isJPG;
    },
    onUploadRemove(file, fileList) {
      this.userInfo.newAddFileId = [];
      this.isHideUploadEdit = fileList.length >= 2;
    },

    // 取消认证
    cancelBut() {
      this.$confirm(`确定取消${ this.userInfo.realName || "无名"}的用户认证`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        userVerified({
          type: 2,
          userId: this.userId,
        }).then(({ code }) => {
          if (code == 200) {
            this.$message({ type: "success", message: `取消认证成功！`, duration: 3000 });
            this.close()
            this.$emit("onrefresh");
          } else {
            this.$message({ type: "error", message: `操作失败！`, duration: 3000 });
          }
        });
      });
    },
    // 保存并更新
    saveConfirm(userInfo){
      this.submitForm(userInfo)
    },
    // 认证通过---查看认证---查询数据
    async getCardInfo() {
      this.verifiedLoading = true;
      let res = await onlineauthentication({ userId:this.userId });
      if (res && res.data && res.data.content) {
        let newAddFile = res.data.content.newAddFile
        if(newAddFile){
          for(let i in newAddFile){
            this.avatarPreviewList.push({ name: "", url: newAddFile[i] });
          }
          this.userInfo.newAddFileId = res.data.content.newAddFileId
        }
        if(res.data.content.mobile){
          this.userInfo.mobile = res.data.content.mobile
        }
        let infoTmp = res.data.content.authenticationBossInfoVo
        this.userInfo.realName = infoTmp.realName
        this.userInfo.city = infoTmp.city
        // 品牌
        this.userInfo.shopId = infoTmp.shopId
        this.userInfo.shopShortName = infoTmp.shopShortName
        // 门店
        this.userInfo.storeId = infoTmp.storeId
        this.userInfo.storeName = infoTmp.storeShortName

        // 认证责任人
        this.userInfo.saleUserId=res.data.content.saleUserId, // 责任人id
        this.userInfo.saleUserName=res.data.content.saleUserName, // 认证责任人

        this.userInfo.storeAddr = infoTmp.storeAddr
        this.verifiedLoading = false;
      } else {
        console.log("接口异常");
      }
    },
  },
};
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
